const app = getApp();

if (app.data.token === '') {
  wx.showToast({
    title: '请先登录',
    icon: 'none'
  });
  wx.redirectTo({
    url: '/pages/login/index',
  });
}

export function __get(url, params = {}, response) {
  wx.request({
    url: app.data.baseUrl + url,
    method: 'GET',
    data: params,
    header: {
      Authorization: 'Bearer ' + app.data.token
    },
    success: res => {
      if (res.statusCode === 200) {
        response(res.data.data);
      } else {
        wx.showToast({
          title: res.data.errors[0]['message'],
          icon: 'none'
        })
      }
    }
  })
}

export function __post(url, data, response) {
  wx.showLoading({
    title: '正在提交，请稍后。。。',
  });
  wx.request({
    url: app.data.baseUrl + url,
    method: 'POST',
    header: {
      Authorization: 'Bearer ' + app.data.token
    },
    data: data,
    success: res => {
      if (res.statusCode === 200) {
        response(res.data.data);
      } else {
        wx.showToast({
          title: res.data.errors[0]['message'],
          icon: 'none'
        })
      }
    },
    complete: () => {
      wx.hideLoading();
    }
  })
}

export function __put(url, data, response) {
  wx.showLoading({
    title: '正在提交，请稍后。。。',
  });
  wx.request({
    url: app.data.baseUrl + url,
    method: 'PUT',
    header: {
      Authorization: 'Bearer ' + app.data.token
    },
    data: data,
    success: res => {
      if (res.statusCode === 200) {
        response(res.data.data);
      } else {
        wx.showToast({
          title: res.data.errors[0]['message'],
          icon: 'none'
        })
      }
    },
    complete: () => {
      wx.hideLoading();
    }
  })
}

export function __delete(url, response) {
  wx.showLoading({
    title: '正在提交，请稍后。。。',
  });
  wx.request({
    url: app.data.baseUrl + url,
    method: 'DELETE',
    header: {
      Authorization: 'Bearer ' + app.data.token
    },
    success: res => {
      if (res.statusCode === 200) {
        response(res.data.data);
      } else {
        wx.showToast({
          title: res.data.errors[0]['message'],
          icon: 'none'
        })
      }
    },
    complete: () => {
      wx.hideLoading();
    }
  })
}

export function __upload(imgType, path, response) {
  wx.showLoading({
    title: '正在上传图片,请稍等...',
  })
  wx.uploadFile({
    url: app.data.baseUrl + 'files',
    filePath: path,
    name: 'image',
    formData: {
      imgType: imgType
    },
    success: res => {
      if (res.statusCode === 200) {
        const data = JSON.parse(res.data);
        response(data.data);
      } else {
        wx.showToast({
          title: res.data.errors[0]['message'],
          icon: 'none'
        });
      }
    },
    complete: () => {
      wx.hideLoading();
    }
  })
}